import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {Row,Col,Card,Form,Input,Select,Icon,Button,Dropdown,Menu,InputNumber,DatePicker,Modal,message,Tree,TreeSelect,Badge,Divider,Upload,Radio,label,Table,Popconfirm ,TimePicker} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Role.less';

/*基础管理-菜单管理*/
const { MonthPicker, RangePicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
var treeData =[];/*tree  机构 data*/
const getValue = obj =>Object.keys(obj).map(key => obj[key]).join(',');


const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj} = props;
  const {getFieldDecorator} = form;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      	if(fieldsValue.parentId == undefined) { fieldsValue.parentId ="0"}
      	else{	fieldsValue.parentId =fieldsValue.parentId.value;}
				if(fieldsValue.url == undefined) {	fieldsValue.url = ""}
				if(fieldsValue.description == undefined ) {	fieldsValue.description = ""}
				if(fieldsValue.state == undefined) {	fieldsValue.state = 1}
				if(fieldsValue.icon == undefined){	fieldsValue.icon=""}
	      form.resetFields();
	      handleAdd(title,obj.menuId,fieldsValue);
    });
  };
  return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    <Form layout = "horizontal" >
		        <FormItem label="菜单名称"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		            {getFieldDecorator('name', {
		            	 initialValue:obj.name,
		              rules: [{ required: true, message: '菜单名称不能为空!' }],
		            })(<Input placeholder="请输入"/>)}
	          	</FormItem>
         	 	<FormItem label="上级菜单"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		            {getFieldDecorator('parentId',{
		            	 initialValue:obj.parentId == "0" ? " ":obj.parentId,
		            })(<TreeSelect  dropdownMatchSelectWidth      allowClear showSearch labelInValue
						treeNodeFilterProp={"title"}    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}    placeholder="请选择"
						treeData={treeData}>
				    </TreeSelect>)}
		        </FormItem>
		        <FormItem label="菜单类型" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
		            {getFieldDecorator('type', {
		            	initialValue:obj.type==undefined ? "2":obj.type,
		              	rules: [{ required: true, message: '菜单类型不能为空!' }],
		            })(<Select  placeholder="请选择" allowClear>
				      <Option value="1">文件夹</Option>
				      <Option value="2">菜单</Option>
				      <Option value="3">按钮</Option>
				    </Select>)}
		        </FormItem>
		        <FormItem label="状态" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
		            {getFieldDecorator('state', {
		            	initialValue:obj.state==undefined ? "1":obj.state,
		            	rules: [{ required: true, message: '菜单状态不能为空!' }],
		            })(
		            <Select placeholder="请选择" allowClear>
		              <Option value="1">有效</Option>
		              <Option value="0">无效</Option>
		            </Select>
		  			)}
		        </FormItem>
		        <FormItem label="菜单URL" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		            {getFieldDecorator('url', {
		            	initialValue:obj.url,
		            })(<Input placeholder="请输入"/>)}
		        </FormItem>
	          <FormItem label="菜单图标" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		            {getFieldDecorator('icon', {
		            	initialValue:obj.icon==undefined ? "bars":obj.icon,
		            })(<Select  placeholder="请选择菜单类型" allowClear >
					      <Option value="bars" className={styles.optionss}><Icon type="bars" /></Option>
					      <Option value="folder-open" className={styles.optionss}><Icon type="folder-open" /></Option>
					      <Option value="solution" className={styles.optionss}><Icon type="solution" /></Option>
					      <Option value="setting" className={styles.optionss}><Icon type="setting" /></Option>
					      <Option value="bar-chart" className={styles.optionss}><Icon type="bar-chart" /></Option>
					      <Option value="shopping-cart" className={styles.optionss}><Icon type="shopping-cart" /></Option>
					      <Option value="video-camera" className={styles.optionss}><Icon type="video-camera" /></Option>
					      <Option value="team" className={styles.optionss}><Icon type="team" /></Option>
					      <Option value="picture" className={styles.optionss}><Icon type="picture" /></Option>
					      <Option value="pause" className={styles.optionss}><Icon type="pause" /></Option>
					      <Option value="clock-circle" className={styles.optionss}><Icon type="clock-circle" /></Option>
			    	</Select>)}
		        </FormItem>
		        <FormItem label="描述" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
		            {getFieldDecorator('description', {
		            	initialValue:obj.description,
		            })(<Input placeholder="请输入"/>)}
		        </FormItem>
    	</Form>
    </Modal>
  );
});

@connect(({ manamenu, loading,menu }) => ({
  manamenu,
  loading: loading.models.manamenu,
  threeMenu: menu.threeMenu,
}))
@Form.create()
export default class TableList extends PureComponent {
	state = {
	    modalVisible: false,
	    selectedRows: [],
	    formValues: {},
	    obj: "",
	};
  componentDidMount() {
  	/*按钮查询*/
		this.props.dispatch({
			type: 'menu/fetch_three_menu',
		});
  	/*默认查询table 数据*/
		this.props.dispatch({
			type: 'manamenu/fetch_menu',
		});
		/*默认查询tree*/
		this.props.dispatch({
			type: 'manamenu/fetch_menu_tree',
			callback: (res, data) => {
				treeData=[];
				if(res == 1) { //成功
					treeData = data;
				}
			},
		});
  }

	handleSelectRows = rows => {
	    this.setState({
	      selectedRows: rows,
	    });
	};
	/*重置*/
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'manamenu/fetch_menu',});
	}
	/*查询*/
	handleSearch = e => {
	    e.preventDefault();
	    const { dispatch, form } = this.props;
	    form.validateFields((err, fieldsValue) => {
		    if (err) return;
		    const values = {  ...fieldsValue,};
		    this.setState({ formValues: values,});
		 	 	if(values.name==undefined){	values.name=""}
				if(values.parentId==undefined){	values.parentId=""}
				if(values.type==undefined){	values.type=""}
				if(values.url==undefined){	values.url=""}
				if(values.description==undefined){	values.description=""}
				if(values.state==undefined){	values.state=""}
				if(values.updatedAt==undefined){	values.updatedAt=""}
        dispatch({
	        type: 'manamenu/fetch_menu',
	        payload:{...values},
        });
	    });
	};
	/*弹窗*/
  handleModalVisible = (flag,record,title) => {
  	const { selectedRows } = this.state;
	  	if(flag==false){
	  		this.setState({
		      modalVisible: false,
		    });
	  	}else{
	  		var obj={};
		  	if(title=="新建"){
			  	this.setState({
			      modalVisible: !!flag,
			      title: title,
			      obj: obj,
			    });
		  		
		  	}else{
		  		if(record==undefined||Object.keys(selectedRows).length==0){
			    	message.info("还未选择项");
			    }else if(Object.keys(selectedRows).length>1){
			    	message.info("只可选择一项");
			    }else{
			    	var objs={};
			    	if(selectedRows[0].parentId==0){
			    		objs=undefined;
			    	}else{
			    		objs.value=selectedRows[0].parentId+'';
			    		objs.label=selectedRows[0].parentName;
			    	}
			    	selectedRows[0].parentId=objs;
						selectedRows[0].type+=''
						selectedRows[0].state+=''
					  obj=selectedRows[0];
					  this.setState({
			      modalVisible: !!flag,
			      title: title,
			      obj: obj,
			    });
			    }
		  	}
	  	}
  	};
	/*新增,修改*/
	handleAdd = (title,Id,fields) => {
	  	if(title=="新建"){
		    this.props.dispatch({
		      type: 'manamenu/add_menu',
		      payload: {...fields,},
		      callback: (res,resMsg) => {
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}else if(title=="编辑"){
	  		if(Id!=undefined){
	  			this.props.dispatch({
			      type: 'manamenu/edit_menu',
			      payload: {
			      	...fields,
			      	menuId:Id,
			      },
			      callback: (res,resMsg) => {
			      	if(res==1){
			      		message.success(resMsg);
			      	}else{
			      		message.error(resMsg);
			      	}
			      },
			    });
	  		}else{
	  			message.info("还未选择项");
	  		}
	  	}
	    this.setState({
	      modalVisible: false,
	    });
	};
  
  /*删除*/
 	confirmModel=(title,Id)=>{
 		const { dispatch } = this.props;
		const { selectedRows } = this.state;
    if(Id==undefined&&Object.keys(selectedRows).length==0){
    	message.info("还未选择项");
    }else{
    	var Ids=[];
	    if(Id!=undefined){
	    	Ids=Id;
	    }else if(selectedRows!=null){
	    	Ids.push(selectedRows.map(row => row.menuId).join(','));
	    }
	    if(title!="删除"){
	    	var state;
	    	if(title=="禁用"){
	    		state=0;
	    	}else{
	    		state=1;
	    	}
	    	Modal.confirm({
					title: '是否'+title+'选中项状态?',
					okText: '确定',
					cancelText: '取消',
					onOk() {
						/*批量修改状态*/
						dispatch({
							type: 'manamenu/edit_menu_state',
							payload: {
								menuIds: Ids,
								state:state,
							},
							callback: (res, resMsg) => {
								if(res == 1) { 
									message.success(resMsg);
								} else { 
									message.error(resMsg);
								}
							},
						});
					}
				});
	    }else{
	    		Modal.confirm({
				    title: '是否删除当前数据选中',
				    content: '',
				    onOk() {
				      dispatch({
					      type: 'manamenu/remove_menu',
					      payload: {menuIds:Ids,},
					      callback: (res,resMsg) => {
					      	if(res==1){
					      		message.success(resMsg);
					      	}else{
					      		message.error(resMsg);
					      	}
					      },
					  	});
				    },
				});
	    }
	  }
 	}
	renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	      	<Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
           <Col md={8} sm={24}>
            <FormItem label="菜单名称">
              {getFieldDecorator('name')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="父级">
              {getFieldDecorator('parentId')(
                <TreeSelect  dropdownMatchSelectWidth   treeDefaultExpandAll   allowClear
			        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}   placeholder="请选择上级菜单"
			        treeData={treeData}>
			    </TreeSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="类型">
              {getFieldDecorator('type')(
                <Select placeholder="请选择" style={{ width: '100%' }} allowClear>
                  <Option value="1">文件夹</Option>
                  <Option value="2">菜单</Option>
                  <Option value="3">按钮</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="菜单链接">
              {getFieldDecorator('url')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="描述">
              {getFieldDecorator('description')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('state')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="1">有效</Option>
                  <Option value="0">无效</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
         <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
           <Col md={24} sm={48}>
            <FormItem>
	            <span style={{ float: 'right', marginBottom: 24 }}>
	            <Button type="primary" htmlType="submit">查询</Button>
	            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
	            </span>
            </FormItem>
          </Col>
        </Row>
      </Form>
	  );
	}
	render() {
	    const { manamenu: { data },loading,threeMenu} = this.props;
	    const { selectedRows, modalVisible,title,obj } = this.state;
	    const columns = [
    	{	title: '序号',
    		dataIndex: 'menuId',
    		key: 'menuId',
    		width:'70px',
    		render: (text, record, index) => {	return index + 1},
    	},
    	{
    		title: '菜单名称',
    		dataIndex: 'name',
    		key: 'name',
    		width:'100px',
    	}, {
    		title: '菜单类型',
    		dataIndex: 'type',
    		key: 'type',
    		width:'100px',
    		render: (text, record, index) => {
    			if(record.type == 1) {
    				return "文件夹"
    			} else if(record.type == 2) {
    				return "菜单"
    			} else {
    				return "按钮"
    			}
    		}
    	}, {
    		title: '菜单URL',
    		dataIndex: 'url',
    		key: 'url',
    		width:'100px',
    	}, {
    		title: 'icon',
    		dataIndex: 'icon',
    		key: 'icon',
    		width:'70px',
    		render(val) {
    			return <Icon type={val} />
    		},
    	},
    	{
    		title: '描述',
    		dataIndex: 'description',
    		key: 'description',
    		width:'100px',
    	},
    	{
    		title: '状态',
    		dataIndex: 'state',
    		key: 'state',
    		width:'70px',
    		render: (text, record, index) => {
    			if(record.state == 1) {
    				return "有效"
    			} else if(record.state == 0) {
    				return "无效"
    			}
    		}
    	}
    ];
	    const parentMethods = {
	      	handleAdd: this.handleAdd,
	      	handleModalVisible: this.handleModalVisible,
	      	confirmModel:this.confirmModel,
	    };
	    return (
	    	 <PageHeaderLayout title="系统管理/菜单管理">
	      	<Card bordered={false}>
	          <div className={styles.tableList}>
	            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
	            <span> 
	            	{threeMenu.new && <Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')} style={{ marginLeft: 8 }}>新建</Button>}
	            	{threeMenu.edit && <Button type="primary" onClick={() => this.handleModalVisible(true,'','编辑')} style={{ marginLeft: 8 }}>编辑</Button>}
	            	{threeMenu.delete && <Button type="primary" onClick={() => this.confirmModel('删除')} style={{ marginLeft: 8 }}>删除</Button>}
	            	{threeMenu.enable && <Button type="primary"  onClick={() => this.confirmModel('启用')}  style={{ marginLeft: 8 }}>启用</Button>}
					      {threeMenu.enable && <Button  type="ghost"  onClick={() => this.confirmModel('禁用')}  style={{ marginLeft: 8 }}>禁用</Button>}
	            </span>
	            <StandardTable
	              selectedRows={selectedRows}
	              loading={loading}
	              data={data}
	              columns={columns}
	              onSelectRow={this.handleSelectRows}
	            />
	          </div>
	        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
	      </Card>
	       </PageHeaderLayout>
	    );
	}
}
